package com.bootdo.collector.utils;

import com.bootdo.collector.task.AmbariCountJob;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.*;
import java.util.Properties;

public class SSH2 {

    private String host;
    private String username ;
    private String keyFilePath = AmbariCountJob.class.getClassLoader().getResource("id_rsa").getPath();
    private String ip;
    private String port;
    private  Session session;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
        if(host.contains(":")) {
            String[] hosts = host.split(":");
            setIp(hosts[0]);
            this.port = hosts[1];
        } else {
            setIp(host);
            this.port = "22";
        }

    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String run(String cmd) {
        ChannelExec shell = null;
        try {
            shell = (ChannelExec) this.session.openChannel("exec");
        } catch (JSchException e) {
            e.printStackTrace();
        }
        StringBuffer result = new StringBuffer();
        shell.setCommand(cmd);
        try {
            shell.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        InputStream in = null;
        try {
            in = shell.getInputStream();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));
        String tmpStr = "";
        while ((tmpStr = reader.readLine()) != null) {
            result.append(new String(tmpStr.getBytes("gbk"), "UTF-8")).append("\n");
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    public Session connect() throws JSchException {

            JSch jSch = new JSch();
            try {
                jSch.addIdentity(keyFilePath);
            } catch (JSchException e) {
                e.printStackTrace();
            }
            session = jSch.getSession(username, ip, Integer.valueOf(port));
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            session.setTimeout(10000);
            session.connect();
            return session;
    }



}
